﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ModeloGaleriaNET;
using System.Configuration;
using SeguridadGaleria;
using System.ComponentModel;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para ConfigServerWindow.xaml
    /// </summary>
    public partial class ConfigServerWindow : Window
    {
        private string[] permisos = {TiposRoles.CAMBIAR_ACCESO_SERVIDOR, TiposRoles.CAMBIAR_ACCESO_UDDI };
        private Dictionary<string, bool> permisosDatos;
        private ServerConnData data;
        private string originalGestor;
        private string originalUser;
        private string originalPassword;
        private string originalUDDI;
        private int originalTime;
        private int originalSeguridad;
        private bool? success;
        private BackgroundWorker worker;
        private ManejadorRoles roleManager;
        private string user;
        private IAuditoria auditoria;
        private int userId;

        public ConfigServerWindow(string user, int userId)
        {
            InitializeComponent();
            data = ServerConnData.Instance;
            iudTiempoEnvio.Minimum = 1;
            iudTiempoEnvio.Maximum = 100;
            permisosDatos = new Dictionary<string, bool>();
            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            roleManager = ManejadorRoles.Instance;
            this.user = user;
            this.userId = userId;
            auditoria = new AuditoriaBD();
        }

        public bool? Success
        {
            get { return success; }
        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                worker.RunWorkerAsync();
            }
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            bool? value;

            foreach (string s in permisos)
            {
                value = roleManager.CanUse(s, user);
                if (value != null)
                    permisosDatos.Add(s, value.Value);
            }
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            bool value;

            _busyIndicator.IsBusy = false;
            if (permisosDatos == null || permisosDatos.Count != permisos.Length)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("No se han podido obtener los permisos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                tbURLjUDDI.IsEnabled = tbURLServidor.IsEnabled = tbUsuario.IsEnabled = pbPassword.IsEnabled =
                    iudTiempoEnvio.IsEnabled = cbSeguridad.IsEnabled = false;
            }
            else
            {
                originalPassword = pbPassword.Password = data.Password;
                originalUDDI = tbURLjUDDI.Text = data.jUDDI;
                originalGestor = tbURLServidor.Text = data.URLGestor;
                originalUser = tbUsuario.Text = data.User;
                cbSeguridad.SelectedIndex = originalSeguridad = data.Seguridad;
                iudTiempoEnvio.Value = originalTime = (int)data.TimeOut;

                permisosDatos.TryGetValue(permisos[0], out value);
                if (value == false)
                    tbURLServidor.IsEnabled = tbUsuario.IsEnabled = pbPassword.IsEnabled = false;

                permisosDatos.TryGetValue(permisos[1], out value);
                if (value == false)
                    tbURLjUDDI.IsEnabled = false;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (HasChanges())
            {
                if (success == true)
                    data.Save();
                else
                {
                    if (Xceed.Wpf.Toolkit.MessageBox.Show("Ha hecho cambios en los datos de la conexión, ¿desea salir?",
                                        "Descartar cambios",
                                        MessageBoxButton.YesNo,
                                        MessageBoxImage.Question) == MessageBoxResult.No)
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private bool HasChanges()
        {
            if (originalUDDI != tbURLjUDDI.Text ||
                originalUser != tbUsuario.Text ||
                originalPassword != pbPassword.Password ||
                originalGestor != tbURLServidor.Text ||
                originalTime != iudTiempoEnvio.Value ||
                originalSeguridad != cbSeguridad.SelectedIndex)
            {
                return true;
            }
            else
                return false;
        }

        private void tbURLjUDDI_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbURLServidor.Text) && !string.IsNullOrWhiteSpace(tbUsuario.Text) &&
                !string.IsNullOrWhiteSpace(pbPassword.Password) && !string.IsNullOrWhiteSpace(tbURLjUDDI.Text))
                btAceptar.IsEnabled = true;
            else
                btAceptar.IsEnabled = false;
        }

        private void pbPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbURLServidor.Text) && !string.IsNullOrWhiteSpace(tbUsuario.Text) &&
                !string.IsNullOrWhiteSpace(pbPassword.Password) && !string.IsNullOrWhiteSpace(tbURLjUDDI.Text))
                btAceptar.IsEnabled = true;
            else
                btAceptar.IsEnabled = false;
        }

        private void btAceptar_Click(object sender, RoutedEventArgs e)
        {
            data.Seguridad = cbSeguridad.SelectedIndex;
            data.URLGestor = tbURLServidor.Text;
            data.User = tbUsuario.Text;
            data.Password = pbPassword.Password;
            data.jUDDI = tbURLjUDDI.Text;
            data.TimeOut = (uint)iudTiempoEnvio.Value;
            data.Save();
            success = true;
            auditoria.Mensaje(new object[] { }, TiposAuditoria.Ordinal(TiposAuditoria.TIPO_AUDITORIA.CAMBIAR_DIRECCIONES_SERVICIOS),
                userId);
            System.Threading.Thread.Sleep(1000);
            Close();
        }
    }
}
